package com.ruoyi.buss.aop;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Aspect
@Order(5)
@Component
class ControllerLogAspect {
//    private Logger logger = Logger.getLogger(getClass());
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Pointcut("execution(public * com.ruoyi.buss.*.controller..*.*(..))")
    public void controllerLog() {
    }
    @Pointcut("execution(public * com.ruoyi.buss.*.*.controller..*.*(..))")
    public void controllerLogs() {
    }
    @Before("controllerLog() || controllerLogs()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 只记录post方法
//        if("POST".equals(request.getMethod()) || "GET".equals(request.getMethod())){
            // 记录下请求内容
            logger.info("-------------------------------------------------------");
            logger.info("请求IP : " + request.getRemoteAddr() +",请求URL : " + request.getRequestURL());
            logger.info("请求方法 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            // 获取参数, 只取自定义的参数, 自带的HttpServletRequest, HttpServletResponse不管
            if (joinPoint.getArgs().length > 0) {
                for (Object o : joinPoint.getArgs()) {
                    if (o instanceof HttpServletRequest || o instanceof HttpServletResponse) {
                        continue;
                    }
                    logger.info("请求参数 : " + o.toString());
                }
            }
//        }
    }

//    @AfterReturning(returning = "ret", pointcut = "controllerLog()")
//    public void doAfterReturning(Object ret) throws Throwable {
//        // 处理完请求，返回内容
////        JSONObject json = (JSONObject) JSON.toJSON(ret);
//        try {
//            TableDataInfo vo = (TableDataInfo)
//        }catch (Exception e){
//
//        }
//        System.out.println("返回 : " + AjaxResult.success(ret));
//    }
}